<template>
  <Form ref="form" class="xtx-form" :validation-schema="rules" v-slot="{errors}">
    <!-- 测试 -->
    <p>{{errors}}</p>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field v-model="formData.account" name="account" :class="{err:errors.account}" class="input" type="text" placeholder="请输入用户名" />
      </div>
      <div class="error" v-if="errors.account">{{errors.account}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field v-model="formData.mobile" name="mobile" :class="{err:errors.mobile}" class="input" type="text" placeholder="请输入手机号" />
      </div>
      <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field v-model="formData.code" name="code" :class="{err:errors.code}" class="input" type="text" placeholder="请输入验证码" />
        <span class="code" @click="sendCode">{{count===0?'发送验证码':`${count}秒后重发`}}</span>
      </div>
      <div class="error" v-if="errors.code">{{errors.code}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field v-model="formData.password" name="password" :class="{err:errors.password}" class="input" type="password" placeholder="请输入密码" />
      </div>
      <div class="error" v-if="errors.password">{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field v-model="formData.rePassword" name="rePassword" :class="{err:errors.rePassword}" class="input" type="password" placeholder="请确认密码" />
      </div>
      <div class="error" v-if="errors.rePassword">{{errors.rePassword}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { reactive, ref } from 'vue'
import { useCountDown } from '@/hook'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import { message } from '@/components/Message/index.js'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
// 表单校验
const useValidForm = () => {
  // 表单数据
  const formData = reactive({
    account: null,
    mobile: null,
    code: null,
    password: null,
    rePassword: null
  })

  // 校验规则
  const rules = {
    account: schema.accountApi,
    mobile: schema.mobile,
    code: schema.code,
    password: schema.password,
    rePassword: schema.rePassword
  }

  return { formData, rules }
}

// 发送验证码
const useSendCode = (formData) => {
  const form = ref(null)
  const { start, count } = useCountDown(60)
  const sendCode = async () => {
    // 校验手机号
    const valid = schema.mobile(formData.mobile)
    if (valid === true) {
      // 校验通过
      try {
        // 判断是否正在发送验证码
        if (count.value === 0) {
          await userQQPatchCode(formData.mobile)
          // console.log(res)
          // 提示
          message({
            type: 'success',
            text: '发送成功'
          })
          // 开启倒计时
          start()
        }
      } catch (error) {
        message({
          type: 'error',
          text: error.response.data.message
        })
      }
    } else {
      // 校验未通过
      form.value.setFieldError('mobile', valid)
    }
  }

  return { sendCode, form, count }
}

// 提交注册
const register = (form, props, formData) => {
  const store = useStore()
  const router = useRouter()
  const submit = async () => {
    // 整体表单验证
    const res = await form.value.validate()
    // console.log(res)
    if (res.valid) {
      try {
        // 校验成功 调用接口
        const { result } = await userQQPatchLogin({
          unionId: props.unionId,
          ...formData
        })
        // console.log(res)
        // 存储用户信息
        store.commit('user/setProfile', result)
        // 直接跳转至首页
        router.replace('/')
        // 成功提示
        message({
          type: 'success',
          text: '注册成功'
        })
      } catch (error) {
        message({
          type: 'error',
          text: '注册失败'
        })
      }
    }
  }

  return { submit }
}
export default {
  name: 'CallbackPatch',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: {
    Form,
    Field
  },
  setup (props) {
    const { formData, rules } = useValidForm()

    const { sendCode, form, count } = useSendCode(formData)

    const { submit } = register(form, props, formData)

    return { formData, rules, sendCode, form, count, submit }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
